import { app } from 'db://app-game/core/app';
import { generateUUID } from 'db://app-game/core/utils/uuid';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { GameStorage } from '../../../common/config/GameStorage';
import { GameSaveData } from './LocalStorageManager.type';
import { LocalStorageModelComp } from './model/LocalStorageModelComp';

/** 本地缓存管理实例 */
@ecs.register('LocalStorageManager')
export class LocalStorageManager extends ecs.Entity {
  // 数据层
  LSM!: LocalStorageModelComp;

  init() {
    this.add(LocalStorageModelComp);
  }

  /** 加载存档数据 */
  public load(slot: number = 0) {
    try {
      // 1.获取存档信息
      const fileInfo = app.storage.getJson<GameSaveData>(`${GameStorage.Save}_${slot}`);
      if (!fileInfo) {
        this.initNewData();
        app.storage.setUser(this.LSM.data.player.basic.uid);
        app.storage.set(`${GameStorage.Save}_${slot}}`, this.LSM.data);
      }
    } catch (error) {
      console.error('Load File Info:', error);
    }
  }

  /** 初始化存档数据 */
  private initNewData() {
    // 初始化存档数据
    this.LSM.data = {
      player: {
        basic: {
          uid: `${generateUUID()}`,
          avatar: 'default',
        },
      },
    };
  }
}
